<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\api\controller;
use think\Db;

class Group extends Base
{
    protected function Getzimu($str)
    {
        if(empty($str)){
            return '#';
        }
        $fchar = mb_substr($str, 0, 1, 'utf-8');
        // 判断表情    表情长度为4位
        if(strlen($fchar) >= 4 ){
            return '#';
        }
//        print_r($fchar);die;
//        $fchar=ord($str{0});
        if($fchar >= ord('A') && $fchar <= ord('z')){
            return strtoupper($str{0});
        }
        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0})*256+ord($s{1})-65536;
        if($asc >= -20319 && $asc <= -20284) return 'A';
        if($asc >= -20283 && $asc <= -19776) return 'B';
        if($asc >= -19775 && $asc <= -19219) return 'C';
        if($asc >= -19218 && $asc <= -18711) return 'D';
        if($asc >= -18710 && $asc <= -18527) return 'E';
        if($asc >= -18526 && $asc <= -18240) return 'F';
        if($asc >= -18239 && $asc <= -17923) return 'G';
        if($asc >= -17922 && $asc <= -17418) return 'H';
        if($asc >= -17417 && $asc <= -16475) return 'J';
        if($asc >= -16474 && $asc <= -16213) return 'K';
        if($asc >= -16212 && $asc <= -15641) return 'L';
        if($asc >= -15640 && $asc <= -15166) return 'M';
        if($asc >= -15165 && $asc <= -14923) return 'N';
        if($asc >= -14922 && $asc <= -14915) return 'O';
        if($asc >= -14914 && $asc <= -14631) return 'P';
        if($asc >= -14630 && $asc <= -14150) return 'Q';
        if($asc >= -14149 && $asc <= -14091) return 'R';
        if($asc >= -14090 && $asc <= -13319) return 'S';
        if($asc >= -13318 && $asc <= -12839) return 'T';
        if($asc >= -12838 && $asc <= -12557) return 'W';
        if($asc >= -12556 && $asc <= -11848) return 'X';
        if($asc >= -11847 && $asc <= -11056) return 'Y';
        if($asc >= -11055 && $asc <= -10247) return 'Z';
        return "#";
    }
    /**
     * 创建群
     * 参数：1、uid(必须是数组且包含创建人id：要加入这个群的用户id），2、name：群名字，3、thumb：群头像，4、notice：群公告
     * @return string
     */
    public function createGroup(){
        extract(input());
		$uid = explode(',',trim($uid,','));
        if(!$uid){
            return json_encode(['status'=>0,'msg'=>'请选择用户']);
        }
        if(count($uid) < 2){
            return json_encode(['status'=>0,'msg'=>'最少要有两个人']);
        }
        $uidArray = $uid;
        $uid = implode($uid,',');
        $uid = trim($uid,',');
        $uid = ',' . $uid . ',';
        $data = array();
        $data['g_name'] = $name;
        $data['g_id'] = $this->uuid();
        $data['g_user_id'] = $user_id;
        $data['g_uids'] = $uid;
        $data['g_notice'] = $notice;
        $data['g_thumb'] = $thumb;
        $data['g_top_uids'] = ',0,';
        $data['g_no_uids'] = ',0,';
        $data['g_time'] = date('Y-m-d H:i:s');
        Db::startTrans();
        try {
            $groupid = $data['g_id'];
            Db::table('up_group')->insert($data);
            $uids = '';
            foreach ($uidArray as $v) {
                $uids .= "userId={$v}&";
            }

            $res = $this->create($uids,$groupid,$name);

            if ($res['code'] != 200) {
                Db::table('up_group')->where('g_id', $groupid)->delete();
                $status = 0;
                $msg = '新增失败';
            }else{
                $status = 200;
                $msg = $groupid;
            }
            Db::commit();
            $returnData['status'] = $status;
            $returnData['msg'] = $msg;
            return json_encode($returnData);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $returnData['status'] = 0;
            $returnData['msg'] = "新增失败！";
            return json_encode($returnData);
        }
    }

    /**
     * 从群里邀请人的时候，单独做一个查询好友的接口，告知此群你的好友谁已经进来了
     */
    public function selectFriendsForJoinGroup(){
        extract(input());
        $keyword = input('param.keyword');
        $where = array();
        $where['friend_user_id'] = $user_id;
        $where['friend_status'] = 2;
        $where['user_status'] = 1;
        if($keyword!=''){
            $where['user_username|user_phone|f_remark_name'] = array('like','%'.$keyword.'%');
        }
        $list = Db::table('up_friend')->alias('f')
            ->join('up_u_user u','f.friend_other_user = u.user_id','LEFT')
            ->where($where)
            ->field('friend_other_user,user_username,user_image,f_remark_name')
            ->order('f_letter asc')
            ->select();
        if($list){
            foreach ($list as $k=>$v){
                if(empty($v['f_remark_name'])){
                    $list[$k]['f_remark_name'] = $v['user_username'];
                }
                $list[$k]['can'] = 1;
                if(isset($g_id) && $g_id){
                    $have = Db::table('up_group')
                        ->where('g_id',$g_id)
                        ->where('g_uids','like','%,'.$v['friend_other_user'].',%')
                        ->find();
                    if($have){
                        $list[$k]['can'] = 2;
                    }
                }
                //排序
                $str = $list[$k]['f_remark_name'];
                $letter = $this->Getzimu($str);
                $list[$k]['letter'] = $letter;
            }
            $last_names = array_column($list, 'letter');
            array_multisort($last_names, SORT_ASC, $list);
            $start = '';
            $res = array();
            foreach ($list as $k => $v) {
                if ($v['letter'] != $start) {
                    $start = $v['letter'];
                }
                $res[$start][] = $v;
            }
            $jing = array();
            if(isset($res['#'])){
                $jing['#'] = $res['#'];
                unset($res['#']);
            }
            $list = array_merge($res,$jing);
        }

        return  json(array('status'=>200,'msg'=>$list));
    }

    /**
     * 加入群组：加人
     * 参数：1、uid(必须是数组：要加入的这些人的id)，2、群id
     * @return string
     */
    public function joinGroup(){
        extract(input());
        $g = Db::table('up_group')->where('g_id', $groupid)->find();
        $g['g_uids'] = trim($g['g_uids'],',');
        $uids = explode(',',$g['g_uids']);
        $uid = explode(',',trim($uid,','));
        if(!$uid){
            return json_encode(['status'=>0,'msg'=>'请选择用户']);
        }
        if($g['g_status'] != 1){
            return json_encode(['status'=>0,'msg'=>'此群已解散']);
        }
        $same = array_intersect($uids,$uid);
        if($same){
            return json_encode(['status'=>0,'msg'=>'有相同成员']);
        }
        $all = array_merge($uids,$uid);
        if(count($all) > 500){
            return json_encode(['status'=>0,'msg'=>'成员已满']);
        }
        Db::startTrans();
        try {
            $uidstr = '';
            foreach ($uid as $v) {
                $uidstr .= "userId={$v}&";
            }

            $res = $this->joinin($uidstr,$groupid,$g['g_name']);

            if ($res['code'] != 200) {
                $status = 0;
                $msg = '失败';
            }else{
                $ids = implode($uid,',');
                $newids = ',' . $g['g_uids'] . ',' . $ids . ',';
                Db::table('up_group')->where('g_id', $groupid)->update(['g_uids'=>$newids]);
                $status = 200;
                $msg = '成功';
            }
            Db::commit();
            $returnData['status'] = $status;
            $returnData['msg'] = $msg;
            return json_encode($returnData);
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $returnData['status'] = 0;
            $returnData['msg'] = "加入失败！";
            return json_encode($returnData);
        }
    }
    /**
     * 退出群组：踢人（如果群主退出，则解散）
     * 参数：1、uid(必须是数组：退出的这个人的id或者是被踢的这些人的id)，2、groupid(群组id)
     * @return string
     */
    public function outGroup(){
        extract(input());
//        ---------------------------

        $g = Db::table('up_group')->where('g_id', $groupid)->find();
        $g['g_uids'] = trim($g['g_uids'],',');
        $uids = explode(',',$g['g_uids']);
//        ---------------------------

        $uid = explode(',',trim($uid,','));
        if(!$uid){
            return json_encode(['status'=>0,'msg'=>'请选择用户']);
        }

        $o = count($uid)+1;
        $t = count($uids);
//        if(in_array($g['g_user_id'],$uid) || $o>=$t){
        if(in_array($g['g_user_id'],$uid)){
            $res = $this->kill($user_id,$groupid);
            if ($res['code'] != 200) {
                return json_encode(['status'=>0,'msg'=>'解散失败']);
            }else{
                $res = Db::table('up_group')->where('g_id', $groupid)->update(['g_status'=>2]);
                return json_encode(['status'=>200,'msg'=>'解散成功']);
            }
        }else{
            Db::startTrans();
            try {
                $uidstr = '';
                foreach ($uid as $v) {
                    $uidstr .= "userId={$v}&";
                }
                $res = $this->getout($uidstr,$groupid);
                if ($res['code'] != 200) {
                    $status = 0;
                    $msg = '失败';
                }else{
                    $difids = array_diff($uids,$uid);
                    $ids = implode($difids,',');
                    $newids = ',' . $ids . ',';
                    Db::table('up_group')->where('g_id', $groupid)->update(['g_uids'=>$newids]);
                    $status = 200;
                    $msg = '成功';
                }
                Db::commit();
                $returnData['status'] = $status;
                $returnData['msg'] = $msg;
                return json_encode($returnData);
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $returnData['status'] = 0;
                $returnData['msg'] = "失败！";
                return json_encode($returnData);
            }
        }

    }

    /**
     * 我的群聊
     *
     * @return string
     */
    public function myGroup(){
        extract(input());
//        $uid = ',' . $user_id . ',';
        $res = Db::table('up_group')
            ->where('g_uids', 'like',"%,$user_id,%")
            ->where('g_status', 1)
            ->page($page,15)
            ->select();
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 我的某个群聊详情
     * （只有群主才可以减人和更改公告）
     * @return string
     */
    public function myGroupInfo(){
        extract(input());
        $res = Db::table('up_group')
            ->where('g_id', $groupid)
            ->find();
        $res['top'] = 1;//我没有置顶
        $res['no'] = 1;//我没有消息免打扰
        $top_array = explode(',',trim($res['g_top_uids'],','));
        $no_array = explode(',',trim($res['g_no_uids'],','));
        if(in_array($user_id,$top_array)){
            $res['top'] = 2;
        }
        if(in_array($user_id,$no_array)){
            $res['no'] = 2;
        }
        //我在本群的备注
        $res['remark'] = Db::table('up_group_name')
            ->where('gn_g_id',$groupid)
            ->where('gn_user_id',$user_id)
            ->value('gn_name');

        $uids = trim($res['g_uids'],',');
        $users = Db::table('up_u_user')->where('user_id','in',$uids)
            ->field('user_id,user_username,user_image')
            ->page(1,40)
            ->select();
        $users = $this->getGnameRemark($users,$groupid);
        $num = explode(',',$uids);
        $nums = count($num);
        return json_encode(['status'=>200,'msg'=>$res,'users'=>$users,'nums'=>$nums]);
    }


    /**
     * 查看群里所有成员
     * （只有群主才可以减人和更改公告）
     * @return string
     */
    public function myGroupUsers(){
        extract(input());
        $res = Db::table('up_group')
            ->where('g_id', $groupid)
            ->find();
        if(isset($del) && $del==1){ //减人的时候传一下，就看不到我了
            $res['g_uids'] = str_replace(','.$res['g_user_id'].',', ',', $res['g_uids']);
        }
        $uids = trim($res['g_uids'],',');
        $where = array();
        $where['user_id'] = ['in',$uids];
        if(isset($keyword) && $keyword){
            $where['user_username'] = ['like','%'.$keyword.'%'];
        }
        $users = Db::table('up_u_user')
            ->where($where)
            ->field('user_id,user_username,user_image')
//            ->page($page,20)
            ->select();
        $users = $this->getGnameRemark($users,$groupid);
        return json_encode(['status'=>200,'msg'=>$users]);
    }
    /**
     * 查看群里所有成员(不要分页):这个方法应该用不到
     * （只有群主才可以减人和更改公告）
     * @return string
     */
    public function myGroupUsersNoPage(){
        extract(input());
        $res = Db::table('up_group')
            ->where('g_id', $groupid)
            ->find();
        $uids = trim($res['g_uids'],',');
        $users = Db::table('up_u_user')->where('user_id','in',$uids)
            ->field('user_id,user_username,user_image')
            ->select();
        $users = $this->getGnameRemark($users,$groupid);
        return json_encode(['status'=>200,'msg'=>$users]);
    }
    protected function getGnameRemark($users,$groupid)
    {
        if($users){
            foreach ($users as $k=>$v){
                $have = Db::table('up_group_name')
                    ->where('gn_g_id',$groupid)
                    ->where('gn_user_id',$v['user_id'])
                    ->value('gn_name');
                if($have){
                    $users[$k]['user_username'] = $have;
                }
            }
        }
        return $users;
    }
    /**
     * 修改我的群聊
     * （只有群主才可以减人和更改公告）
     * @return string
     */
    public function updateGroup(){
        extract(input());
//        $user_id=6;$groupid='9d2faf99a463c6006ee7bc658823b3fc';$no=2;$name='lalala';
        $data = array();
        $data['g_time'] = date('Y-m-d H:i:s');
        $group = Db::table('up_group')->where('g_id', $groupid)->field('g_user_id,g_top_uids,g_no_uids')->find();
        $own = $group['g_user_id'];
        if(isset($name) && $name){
            if($own != $user_id){
                return json_encode(['status'=>100,'msg'=>'只有群主才有修改权限']);
            }
            $data['g_name'] = $name;
            //更新融云群名称
            $rong = $this->update($groupid,$name);
            if ($rong['code'] != 200) {
                return json_encode(['status'=>100,'msg'=>'更新服务器失败，请刷新重试']);
            }
        }
        if(isset($thumb) && $thumb){
            if($own != $user_id){
                return json_encode(['status'=>100,'msg'=>'只有群主才有修改权限']);
            }
            $data['g_thumb'] = $thumb;
        }
        if(isset($notice) && $notice){
            if($own != $user_id){
                return json_encode(['status'=>100,'msg'=>'只有群主才有修改权限']);
            }
            $data['g_notice'] = $notice;
        }
        //置顶、免打扰、本群昵称
        if(isset($top) && $top){
            if(strstr($group['g_top_uids'],",$user_id,")){
                $data['g_top_uids'] = str_replace(','.$user_id.',', ',', $group['g_top_uids']);
            }else{
                $data['g_top_uids'] = $group['g_top_uids'] . $user_id . ',';
            }
        }
        if(isset($no) && $no){
            if(strstr($group['g_no_uids'],",$user_id,")){
                $data['g_no_uids'] = str_replace(','.$user_id.',', ',', $group['g_no_uids']);
            }else{
                $data['g_no_uids'] = $group['g_no_uids'] . $user_id . ',';
            }
        }
        if(isset($remark) && $remark){
            $two_in = [
                'gn_name' => $remark,
                'gn_g_id' => $groupid,
                'gn_user_id' => $user_id,
                'gn_time' => date('Y-m-d H:i:s')
            ];
            $have = Db::table('up_group_name')
                ->where('gn_g_id',$groupid)
                ->where('gn_user_id',$user_id)
                ->find();
            if($have){
                $res = Db::table('up_group_name')
                    ->where('gn_g_id',$groupid)
                    ->where('gn_user_id',$user_id)
                    ->update($two_in);
            }else{
                $res = Db::table('up_group_name')
                    ->where('gn_g_id',$groupid)
                    ->where('gn_user_id',$user_id)
                    ->insert($two_in);
            }
        }else{
            $res = Db::table('up_group')->where('g_id', $groupid)
                ->update($data);
        }
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>100,'msg'=>'修改失败']);
        }


    }
    /**
     * 根据群的id获取这些群的信息
     *
     * @return string
     */
    public function byIdsGetGroupInfo(){
        $gids = trim($_POST['gids'],',');
        $res = Db::table('up_group')
            ->where('g_id', 'in',$gids)
//            ->where('g_status', 1)
            ->select();
        if($res){
            foreach ($res as $k=>$v){
                $udis = trim($v['g_uids'],',');
                $num = count(explode(',',$udis));
                $res[$k]['num'] = $num;
            }
        }
        return json_encode(['status'=>200,'msg'=>$res]);
    }
    /**
     * 根据群的id获取这些群的信息
     *
     * @return string
     */
    public function getGroupUserInfo(){
        $gids = trim($_POST['gids'],',');
        $res = Db::table('up_group')
            ->where('g_id', 'in',$gids)
//            ->where('g_status', 1)
            ->select();
        if($res){
            foreach ($res as $k=>$v){
                $udis = trim($v['g_uids'],',');
                $num = count(explode(',',$udis));
                $res[$k]['num'] = $num;
            }
        }
        $uids = trim($_POST['uids'],',');
        $user = Db::table('up_u_user')
            ->where('user_id', 'in',$uids)
            ->field('user_id,user_username,user_image')
            ->select();
        return json_encode(['status'=>200,'msg'=>$res,'user'=>$user]);
    }
    /**
     * 我还在不在这个群了
     *
     * @return string
     */
    public function whereami(){
        extract(input());
        $status = Db::table('up_group')
            ->where('g_id', $groupid)
            ->where('g_uids', 'like',"%,$user_id,%")
            ->find();
        $res = Db::table('up_group')
            ->where('g_id', $groupid)
            ->find();
        if($status){
            $res['status'] = 1;//我还在
        }else{
            $res['status'] = 0;//我不在了
        }
        if($res['g_status'] == 2){ //解散比较特殊
            $res['status'] = 0;
        }
        $uids = trim($res['g_uids'],',');
        $users = Db::table('up_u_user')->where('user_id','in',$uids)
            ->field('user_id,user_username,user_image')->select();
        $res['users'] = $users;
        return json_encode(['status'=>200,'msg'=>$res]);

    }

}